<template>
  <div class="task-container">
    <div class="task-header">
      <van-search v-model="value" placeholder="请输入搜索关键词" />
    </div>

    <div class="task-info__content">
      <van-pull-refresh v-model="refreshing" @refresh="refresh">
        <van-list
          v-model="loading"
          :finished="finished"
          @load="loadNextPage"
          loading-text="加载中..."
          finished-text="没有更多了"
        >
          <van-cell v-for="item in state.taskList" :key="item.id">
            <CustomCard :item="item" @click="goDetail(item)" />
          </van-cell>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { getUserTaskListForPages } from "../../../service/task";
import CustomCard from "@/components/CustomCard/Index.vue";
import router from "../../../router";

const refreshing = ref(false); // 下拉刷新状态
const loading = ref(false); // 加载更多状态
const finished = ref(false); // 是否已加载完所有数据
const pageNum = ref(1); // 当前页码
const total = ref(0); // 总数据条数
const pages = ref(0); // 总页数

const state = reactive({
  taskList: [],
});

// 刷新数据
const refresh = () => {
  refresh.value = true;
  // 重新加载第一页数据
  pageNum.value = 1;
  loadData();
};

// 加载下一页数据
const loadNextPage = () => {
  if (loading.value || finished.value) return;
  loading.value = true;
  loadData();
};

// 模拟加载数据
const loadData = async () => {
  const { data, status } = await getUserTaskListForPages({
    pageNum: pageNum.value,
  });
  if (status == 0) {
    // 判断是否已加载完所有数据
    loading.value = false;
    refresh.value = false;
    total.value = data.total;
    pages.value = data.pages;
    finished.value = pageNum.value >= pages.value;

    if (pageNum.value === 1) {
      // 如果是第一页，直接替换列表数据
      state.taskList = data.list;
    } else {
      // 如果是后续页，追加到列表数据
      state.taskList = [...state.taskList, ...data.list];
    }
    pageNum.value++;
  } else {
    state.taskList = [];
    loading.value = false;
    finished.value = false;
    refresh.value = false;
  }
};

const goDetail = (item) => {
  router.push({
    name: "taskDetail",
    query: {
      id: item.id,
    },
  });
};
</script>

<style lang="less" scoped>
.task-container {
  height: calc(100% - 46px);

  display: flex;
  flex-direction: column;

  .task-info__content {
    flex: 1;
    height: 100%;
    overflow-y: scroll;
  }
}
</style>
